package com.bluesky.javawebbrowser.domain.html;

import javax.swing.JPanel;

import org.apache.log4j.Logger;

import com.bluesky.javawebbrowser.domain.html.parser.HtmlParser;
import com.bluesky.javawebbrowser.domain.html.parser.ParseResult;
import com.bluesky.javawebbrowser.domain.html.parser.RegexHtmlParser;
import com.bluesky.javawebbrowser.domain.html.tags.Tag;
import com.bluesky.javawebbrowser.domain.html.tags.TagType;

public class HtmlPage {
	private static Logger logger = Logger.getLogger(HtmlPage.class);

	private Tag root;
	private ParseResult parseResult;

	public HtmlPage() {

	}

	public HtmlPage(String htmlText, boolean restrict) {
		parse(htmlText, restrict);

	}

	public HtmlPage(String htmlText) {
		parse(htmlText, false);

	}

	private void parse(String htmlText, boolean restrict) {
		if (htmlText == null)
			htmlText = "";

		HtmlParser parser = new RegexHtmlParser();
		parseResult = parser.parse(htmlText, true);

		if ((restrict && (parseResult.getWarnningCount() > 0) || parseResult
				.getErrorCount() > 0)) {
			logger.warn(parseResult.getRoot().toTagTree());
			throw new RuntimeException("fail to parse.");
		}

		root = parseResult.getRoot();
	}

	public boolean isParseFinish() {
		Tag tag = root.getByTagType(TagType.HTML);
		if (tag != null && tag.getFoot() != null)
			return true;
		else
			return false;
	}

	public String toHtml() {
		return root.toHtml();
	}

	public Tag getRoot() {
		return root;
	}

	public void setRoot(Tag root) {
		this.root = root;
	}

	public ParseResult getParseResult() {
		return parseResult;
	}

	public void setParseResult(ParseResult parseResult) {
		this.parseResult = parseResult;
	}

	public void paint(JPanel panel) {
		Tag htmlTag = root.getByTagType(TagType.BODY);
		panel.add(htmlTag.getComponent());
	}

	public Tag getTagById(String id) {
		return root.getById(id);
	}
}
